import axios from "axios";
import router from "../router";
import { Notification } from "element-ui";

axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";

// 请求拦截器
axios.interceptors.request.use(
  request => {
    // 登录页面不要token 可如下设置

    if (router.currentRoute.name === "login") {
      return request;
    }

    // // header存入token信息
    if (localStorage.getItem("token")) {
      request.headers.common["token"] = localStorage.getItem("token");
      return request;
    }
    return request;
  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    if (response.data.code === -401) {
      /*  localStorage.clear();
       router.replace({
         path: "/login"
       }); */
      /* Notification({
        title: "警告",
        message: "登录信息失效，请重新登录。",
        type: "warning"
      }); */
    } else if (response.data.code < 0) {
      Notification({
        title: "警告",
        message: response.data.message,
        type: "warning"
      });
    }
    return response
  },
  error => {
    Notification({
      title: "警告",
      message: error.msg || error.message || error,
      type: "warning"
    });
    return error;
  }
);

// Post
export default {
  askPost: function (url, params,config) {
    return new Promise((resolve, reject) => {
      axios
        .post(url, params,config)
        .then(
          response => {
            resolve(response.data);
          },
          err => {
            reject(err);
          }
        )
        .catch(error => {
          reject(error);
        });
    });
  },

  // Get
  askGet: function (url, queryInfo) {
    return new Promise((resolve, reject) => {
      axios
        .get(url, { params: queryInfo })
        .then(
          response => {
            resolve(response.data);
          },
          err => {
            reject(err);
          }
        )
        .catch(error => {
          reject(error);
        });
    });
  },

  // Put
  askPut: function (url, params) {
    return new Promise((resolve, reject) => {
      axios
        .put(url, params)
        .then(
          response => {
            resolve(response.data);
          },
          err => {
            reject(err);
          }
        )
        .catch(error => {
          reject(error);
        });
    });
  },

  // Delete
  askDelete: function (url, query) {
    return new Promise((resolve, reject) => {
      axios
        .delete(url, { params: query })
        .then(
          response => {
            resolve(response.data);
          },
          err => {
            reject(err);
          }
        )
        .catch(error => {
          reject(error);
        });
    });
  }
};
